//
//  LRXLoginView.m
//  路人侠
//
//  Created by zhangxulong on 2/18/16.
//  Copyright © 2016 zhangxulong. All rights reserved.
//

#import "LRXLoginView.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "KLSwitch.h"
@interface LRXLoginView()<UITextFieldDelegate>
@property (nonatomic,weak) UITextField * passText;
@property (nonatomic,weak) UITextField * userIdText;

@end

@implementation LRXLoginView

+ (instancetype)layoutLoginViewSubviews
{
    return [[LRXLoginView alloc]initSubViews];
}

- (instancetype)initSubViews
{
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
        self.textFiels = [NSMutableArray array];
        CGFloat labelX = 37 * wScale;
        CGFloat fontSize = 27 * hScale;   //字体的大小
        CGFloat viewW = MainScreenW * 0.7 - 2 * labelX;
        
        //无边框的TextField
        UITextField * userNameText = [[UITextField alloc]init];
        userNameText.returnKeyType = UIReturnKeyNext;
        self.userIdText = userNameText;
        userNameText.placeholder = @"请输入账号/手机号";
        userNameText.font = [UIFont systemFontOfSize:fontSize];
        userNameText.borderStyle = UITextBorderStyleNone;
        CGFloat userNameTextY = 90 * hScale;
        userNameText.tag = 0;
        userNameText.frame = CGRectMake(labelX, userNameTextY, viewW, 30 * hScale);
        userNameText.delegate = self;
        
        //添加分隔线
        UIImageView * lineView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line"]];
        CGFloat lineViewY = userNameTextY + 10 * hScale + userNameText.frame.size.height;
        lineView.frame = CGRectMake(labelX, lineViewY, viewW , 2 * hScale);
    
        
        //无边框的TextField
        UITextField * passText = [[UITextField alloc]init];
        
        passText.secureTextEntry = YES;
        passText.placeholder = @"登录密码";
        passText.font = [UIFont systemFontOfSize:fontSize];
        passText.borderStyle = UITextBorderStyleNone;
        CGFloat passTexttY = CGRectGetMaxY(lineView.frame) + 40 * hScale;
        passText.frame = CGRectMake(labelX, passTexttY, viewW - 60 * wScale, 30 * hScale);
        passText.tag = 1;
        self.passText = passText;
        self.passText.delegate = self;
        
        
        CGFloat passSwitchX = CGRectGetMaxX(lineView.frame) - 60 * wScale;
        
        KLSwitch * passSwich = [[KLSwitch alloc]initWithFrame:CGRectMake(passSwitchX, passTexttY - 10 * hScale, 60 * wScale, 40 * hScale) didChangeHandler:^(BOOL isOn) {
            if (isOn) {
                self.passText.secureTextEntry = NO;
            }
            else
            {
                self.passText.secureTextEntry = YES;
            }
        }];
        [passSwich setOnTintColor:mainColor];
        

        
        //添加分隔线
        UIImageView * lineView2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"line"]];
        CGFloat lineViewY2 = CGRectGetMaxY(passText.frame) + 10 * hScale;
        lineView2.frame = CGRectMake(labelX, lineViewY2, viewW , 2 * hScale);
        
        UIButton * loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [loginBtn setTitle:@"登陆" forState:UIControlStateNormal];
        loginBtn.titleLabel.font = [UIFont systemFontOfSize:25 * hScale];
        
        [loginBtn setTitleColor:mainColor forState:UIControlStateNormal];
        CGFloat loginBtnY = lineViewY2 + 60 * hScale;
        [loginBtn sizeToFit];
        
        loginBtn.center = CGPointMake(MainScreenW * 0.7 * 0.5, loginBtnY);
        [loginBtn addTarget:self action:@selector(loginBtnTouchInside) forControlEvents:UIControlEventTouchUpInside];
        
        userNameText.tag = 0;
        passText.tag = 1;
        
        [self.textFiels addObject:userNameText];
        [self.textFiels addObject:passText];
        
        [self addSubview:passSwich];
        [self addSubview:loginBtn];
        
        [self addSubview:userNameText];
        [self addSubview:lineView];
        
        [self addSubview:passText];
        [self addSubview:lineView2];
        
        
    }
    return self;
}


//登陆
- (void)loginBtnTouchInside
{
    NSString * userName = self.userIdText.text;
    NSString * passText = self.passText.text;
    
    if (userName.length && passText.length) {
        
        NSDictionary * paramDic = @{@"account":userName,@"password":passText,@"registration_id":registrationID};
        
        [MBProgressHUD showMessage:@"正在登陆"];
        
        AFHTTPSessionManager * manger = [AFHTTPSessionManager manager];
        
        manger.requestSerializer.timeoutInterval = 10.0f;
        
        [manger POST:routeLoginUrl parameters:paramDic progress:nil  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [MBProgressHUD hideHUD];
  
            NSInteger loginStateCode = [responseObject[@"data"][@"status_code"] integerValue];
            NSLog(@"%@",responseObject);
            
            //登录成功后 条跳转到 首页
            if (loginStateCode == 1) {
                //用户个人信息归档
                LRXUserModel * userInfo = [LRXUserModel userModelWithDic:responseObject];
                AppDelegate * appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                appDelegate.userRole = [userInfo.role integerValue];
                
                //用户信息保存到本地上
                [NSKeyedArchiver archiveRootObject:userInfo toFile:userFilePath];
                //保存账号
                NSUserDefaults *defualts = [NSUserDefaults standardUserDefaults];
                [defualts setObject:self.userIdText.text forKey:@"ident"];
                [defualts synchronize];
                [self loginSuccess];
                
            }
            else if(loginStateCode == 2) {
                
                 [MBProgressHUD showError:@"密码错误"];
            }
            else if(loginStateCode == 3)
            {
                [MBProgressHUD showError:@"账号未注册"];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"网络连接失败"];
        }];
        
    }
    else{
        [MBProgressHUD showError:@"密码或账号不能为空"];
    }

}

- (void)loginSuccess
{
    if ([self.remindDelegate respondsToSelector:@selector(loginSuccess)]) {
        //获取LRXMenuView 的单例对象
        [[LRXMenuView shareInstance] viewDidLoad];
        [self.remindDelegate loginSuccess];
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.passText becomeFirstResponder];
    return YES;
}



@end
